/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * chatSERIAL.java
 *
 * Created on 10/04/2012, 09:33:04 PM
 */
package vista;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import comunicacion.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;
import javax.swing.JFileChooser;

/**
 *
 * @author Baculima
 */
public class chatSERIAL extends javax.swing.JFrame {

    /** Creates new form chatSERIAL */
    InputStream in;
    OutputStream out;
    String nombre;
    String usuario1;
    String usuario2;
    String nomLog;
    String nomArch;
    File archivo;
    double tamArch;
    boolean bandArch = false;
    SerialReader lectura = new SerialReader(this.in);
    Thread hiloLectura;

    public chatSERIAL(InputStream in, OutputStream out, String usuario1, String usuario2) {  //invita /// cuando invitan
        this.in = in;
        this.out = out;
        this.usuario1 = usuario1;
        this.usuario2 = usuario2;
        lectura = new SerialReader(this.in);
        hiloLectura = new Thread(lectura);
        initComponents();

        hiloLectura.start();
        lblyo.setText(usuario1);
        lblconectado.setText(usuario2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtconversa = new javax.swing.JTextArea();
        cmdenviar = new javax.swing.JButton();
        txtenviar = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        lblConectado = new javax.swing.JLabel();
        cmdEnviar = new javax.swing.JButton();
        Progreso = new javax.swing.JProgressBar();
        jButton2 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblyo = new javax.swing.JLabel();
        lblconectado = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Mensajeria instantanea UCUENCA");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
                formWindowLostFocus(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Traditional Arabic", 3, 18)); // NOI18N
        jLabel1.setText("CHAT - PUERTO SERIAL RS232");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 30, 310, -1));

        txtconversa.setColumns(20);
        txtconversa.setRows(5);
        jScrollPane1.setViewportView(txtconversa);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 70, 290, 133));

        cmdenviar.setText("ENVIAR");
        cmdenviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdenviarActionPerformed(evt);
            }
        });
        getContentPane().add(cmdenviar, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 220, -1, -1));

        txtenviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtenviarActionPerformed(evt);
            }
        });
        txtenviar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtenviarKeyPressed(evt);
            }
        });
        getContentPane().add(txtenviar, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, 210, 29));
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(337, 114, -1, -1));
        getContentPane().add(lblConectado, new org.netbeans.lib.awtextra.AbsoluteConstraints(337, 141, -1, -1));

        cmdEnviar.setText("Enviar Archivo");
        cmdEnviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdEnviarActionPerformed(evt);
            }
        });
        getContentPane().add(cmdEnviar, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 260, 110, -1));
        getContentPane().add(Progreso, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 260, 200, 20));

        jButton2.setText("Traer Archivo");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 260, 100, -1));

        jLabel5.setText("CHAT CON:");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 140, -1, -1));

        jLabel6.setText("CONECTADO COMO");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 80, -1, -1));
        getContentPane().add(lblyo, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 100, 100, 20));
        getContentPane().add(lblconectado, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 170, 100, 20));

        getAccessibleContext().setAccessibleName("JFrame2");
        getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtenviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtenviarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtenviarActionPerformed

    private void txtenviarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtenviarKeyPressed
        // TODO add your handling code here

        if (evt.getKeyCode() == 10) {
            cmdenviar.doClick();
        }



    }//GEN-LAST:event_txtenviarKeyPressed

    private void cmdenviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdenviarActionPerformed
        // TODO add your handling code here:
        String cadena = usuario1 + " dice: " + txtenviar.getText();//anexa el nombre de loggin y envia el mensaje

        enviarMensaje("11$" + usuario2 + "$chat#" + usuario2 + "#" + usuario1 + "#" + cadena + "#");


        txtconversa.setText(txtconversa.getText() + "\n" + cadena);

    }//GEN-LAST:event_cmdenviarActionPerformed

    private void cmdEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEnviarActionPerformed
        // TODO add your handling code here:

        JFileChooser file = new JFileChooser();
        if (file.showOpenDialog(null) == JFileChooser.APPROVE_OPTION);
        {
            archivo = file.getSelectedFile();
            String nombre = archivo.getName();
            String cadena = "11$"+usuario2+"$FileSend#" + "#" + nombre + "#" + String.valueOf(archivo.length())+"#";
            enviarMensaje(cadena);
            txtconversa.setText(txtconversa.getText() + "\n" + "Esperando Respuesta" + "\n");
            txtenviar.setEnabled(false);
            cmdenviar.setEnabled(false);

        }

    }//GEN-LAST:event_cmdEnviarActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
    hiloLectura.stop();
}//GEN-LAST:event_formWindowClosed

private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus
    // TODO add your handling code here:
    hiloLectura.stop();
}//GEN-LAST:event_formWindowLostFocus

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
        hiloLectura = new Thread(lectura);
        hiloLectura.start();
}//GEN-LAST:event_formWindowGainedFocus
    public class SerialReader implements Runnable { //hilo prara lectura

        InputStream entrada;

        public SerialReader(InputStream in) {
            this.entrada = in;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            try {
                String mensaje = "";
                String cadena = "";
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                Conversion_archivos conv = new Conversion_archivos();
                boolean band = true;//mietras haya bits en el buffer los anexa en una cadena
                while ((len = this.entrada.read(buffer)) > -1) {
                    if (bandArch == true) {

                        bos.write(buffer, 0, len);
                        //System.out.println(bos.size()+"---->"+tamArch);
                        int pors = (int) (bos.size() / (tamArch) * 100);
                        Progreso.setValue(pors);
                        if (bos.size() == tamArch) {
                            bandArch = false;
                            conv.convertir_bytes(bos.toByteArray(), nomArch);
                            nomArch = "";
                            tamArch = 0;
                            txtenviar.setEnabled(true);
                            cmdenviar.setEnabled(true);
                            bos = new ByteArrayOutputStream();
                            cadena = "";
                            txtconversa.setText(txtconversa.getText() + "Se recibio el archivo: " + "\n");
                            Progreso.setValue(0);
                        }
                    }
                    if (len > 0) {
                        // System.out.print(len);
                        mensaje = (new String(buffer, 0, len));
                        cadena += mensaje;
                        //System.out.println(mensaje);
                    }

                    if (cadena.contains("$Log#") && lblConectado.getText().length() == 0 && cadena.contains("?#0"))//si recibe una cadena de login muestra en conectados
                    {
                        StringTokenizer tokens = new StringTokenizer(cadena, "#"); //divide la caena de login y saca el nombre
                        tokens.nextToken();
                        enviarMensaje(nomLog);

                        lblConectado.setText(tokens.nextToken());
                    } else if (cadena.contains("$AceptFile#") && cadena.contains("\n")) {
                        txtconversa.setText(txtconversa.getText() + "Transfiriendo " + nomArch);
                        enviarMensaje("00$BeginSend#"+usuario2);
                        if (enviaArchivo(conv.a_bytes(archivo)) == true) {
                            txtenviar.setEnabled(true);
                            cmdenviar.setEnabled(true);
                            Progreso.setValue(0);

                        }

                    } else if (cadena.contains("$DeclineFile#") && cadena.contains("\n")) {
                        txtconversa.setText(txtconversa.getText() + "No se acepto la transferencia" + "\n");
                    } else if (cadena.contains("$FileSend#") && cadena.contains("?#0")) {
                        StringTokenizer tokens = new StringTokenizer(cadena, "#");
                        tokens.nextToken();
                        nomArch = tokens.nextToken();
                        String tok = tokens.nextToken();
                        tamArch = Double.parseDouble(tok);

                        if (JOptionPane.showConfirmDialog(rootPane, "Desea aceptar " + nomArch + "(" + tamArch + ")" + " de " + lblConectado.getText(), "Recibir Archivo", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                            enviarMensaje("11$"+usuario2+"$AceptFile#");
                            bandArch = true;
                            txtenviar.setEnabled(false);
                            cmdenviar.setEnabled(false);

                        } else {
                            enviarMensaje("11$"+usuario2+"$DeclineFile#");

                        }

                    } else if (cadena.contains("dice") && len > 0 && !mensaje.contains("$Log#") && !cadena.equals("$") && bandArch == false && cadena.contains("?#0")) //si no es el nombre de login muestra el mensaje en la ventana dee chat
                    {
                        String mostrar=""; 
                        StringTokenizer tokens = new StringTokenizer(cadena, "#");
                            tokens.nextToken();
                            tokens.nextToken();
                            tokens.nextToken();
                      
                                mostrar = tokens.nextToken();

                                System.out.println(mostrar);

                        txtconversa.setText(txtconversa.getText() +"\n"+ mostrar);
                        cadena = "";
                    }
                    if (len > 0 && cadena.contains("?#0")) {
                        System.out.print("cadena-/////>>>" + cadena);
                        cadena = "";
                    }


                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
            }
        });
    }

    public void enviarMensaje(String cadena) {

        cadena = cadena + "?#0\n";

        
            try {
                

                this.out.write(cadena.getBytes());//envia la cadena byte por byte
                
            } catch (IOException ex) {
                Logger.getLogger(chatSERIAL.class.getName()).log(Level.SEVERE, null, ex);
            }
        
    }

    private boolean enviaArchivo(byte[] arch) {
        //System.out.print(arch.length);
        for (int i = 0; i < arch.length; i++) {
            try {

                this.out.write(arch[i]);//envia la cadena byte por byte
            } catch (IOException ex) {
                Logger.getLogger(chatSERIAL.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
            int pors = (int) ((double) i / (arch.length) * 100);
            Progreso.setValue(pors);

        }
        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JProgressBar Progreso;
    private javax.swing.JButton cmdEnviar;
    private javax.swing.JButton cmdenviar;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblConectado;
    private javax.swing.JLabel lblconectado;
    private javax.swing.JLabel lblyo;
    private javax.swing.JTextArea txtconversa;
    private javax.swing.JTextField txtenviar;
    // End of variables declaration//GEN-END:variables
}
